//
//  DataTool.swift
//  MyWeiBo
//
//  Created by mac on 15/3/3.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit

class BaseTool: NSObject {
   
}

class AccountTool: BaseTool {
    // 归档存放的路径
    static let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last as! String).stringByAppendingPathComponent("account.plist")
    static var currAccount: Account?
    
    // MARK: 保存账户
    class func saveAccount(account: Account)  -> Bool{
       let result =  NSKeyedArchiver.archiveRootObject(account, toFile: path)
        self.currAccount = account
        return result
    }
    
    class func getAccountFromLoacl() -> Account? {
        var account: AnyObject?
        if account == nil {
            account = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
        } 
        if (account == nil || (account as! Account).isExpire) {
            return nil
        }
        return account as? Account
    }
}


class ImageTool: BaseTool {
    
    ///  根据传进来的 url 集合来缓存图片到本地
    ///
    ///  :param: statues  数据模型集合
    ///  :param: complete 完成的回调
    class func saveImagesToLocalWithStatues(statues: [Status], complete: ( () -> () )) {
        var urls = [String]()
        for item in statues {
            urls.append(item.user!.profile_image_url!)
            if let itemUrls = item.statusPictureURL {
                for url in itemUrls {
                    urls.append( url.thumbnail_pic! )
                }
            }
        }
        SimpleNetWork.shareInstance.downLoadImages(urls) { (imageInfos: [ImageDownLoadComplete]) -> () in
            complete()
        }
    }
    
    ///  首先检查缓存路径集合中时候有本地路径,如果有证明了之前已经缓存成功
    ///  如果没有的就下载,注意,下载有可能失败,所以返回的可能为可选值
    ///  :param: urlString 图片的路径
    ///
    ///  :returns: 拿到的图片
    class func imageWithURLString( urlString: String, complete: (image: UIImage?) -> () ) {
        SimpleNetWork.shareInstance.downLoadImageWithURLString(urlString) { (urlString, imagePath, image, error) -> () in
            complete(image: image)
        }
    }
    
    class func getImageFromLocalWithURLString(urlString: String) -> UIImage? {
        return SimpleNetWork.shareInstance.getImageFromLocalWithURLString(urlString)
    }
 
}